package com.mol.market.ui_v4;

import java.util.HashMap;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.ApiResponse;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.DBUtils;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.BuyLog;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.common.widget.OnScrollChangedListener;
import com.mol.market.ui.ChargeTypeListActivity;
import com.mol.market.ui.PayMainActivity;

/**
 * 产品详细页。<br>
 * <p/>
 * 同时支持横竖屏，竖屏采用单列布局，横屏采用双列布局。<br>
 * <p/>
 * Author: Andrew.Wang
 * Date  : 12-12-10
 */
public class ProductDetailActivity extends BaseActivity
        implements ApiAsyncTask.ApiRequestListener, OnScrollChangedListener,
        LoaderManager.LoaderCallbacks<ApiResponse> {

    private static final String ACTION_PID = "pid";
    private static final String ACTION_PACKAGE_NAME = "pkgName";
    private static final String PARAM_TITLE = "appName";
    private static final String PARAM_ICON = "icon";

    private String mProductName;
    private String mProductId;
    private String mProductPackageName;
    private String mProductSource;

    private ProductDetail mProduct;

    private ProgressBar mProgressBar;

    private ProductFragment mProductFragment;

    private static final int ACTION_LOAD_DETAIL = 0;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case ACTION_LOAD_DETAIL: {

                    loadProductFragment();
                    break;
                }
            }
        }
    };

    /**
     * 加载产品信息Fragment
     */
    private void loadProductFragment() {
        //fix bug by Chaos at 2013/03/19
        //修复了论坛附件下载失败时，点击通知栏崩溃的Bug。
        //因为论坛附件无法获取产品详情
        if(mProductFragment == null && mProduct == null){
            Utils.makeEventToast(getApplicationContext(), 
                    getString(R.string.label_not_found), true);
            onBackPressed();
            return ;
        }
        
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.disallowAddToBackStack();

        Bundle args = new Bundle();
        args.putSerializable(Constants.EXTRA_PRDUCT_DETAIL, mProduct);
        if (mProductFragment == null) {
            mProductFragment = (ProductFragment) Fragment.instantiate(
                    ProductDetailActivity.this, ProductFragment.class.getName(), args);
        }
        ft.replace(R.id.product_detail_layout, mProductFragment);
        ft.commit();
        mProgressBar.setVisibility(View.GONE);
    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_product_detail);
        Intent i = getIntent();

        mProductName = i.getStringExtra(Constants.EXTRA_PRODUCT_NAME);
        mProductId = i.getStringExtra(Constants.EXTRA_PRODUCT_ID);
        mProductSource = i.getStringExtra(Constants.EXTRA_SOURCE_TYPE);
        mProductPackageName = i.getStringExtra(Constants.EXTRA_PACKAGE_NAME);

        initActionBar(mProductName);

        // 加载应用详细信息
        if (checkBarcode(i)) {

            if (TextUtils.isEmpty(mProductPackageName)) {
                // 通过产品ID来获取内容
                boolean isPush = i.getBooleanExtra(Constants.EXTRA_APP_PUSH, false);
                if (isPush) {
                    String nid = i.getStringExtra(Constants.EXTRA_APP_NID);
                    String rule = i.getStringExtra(Constants.EXTRA_APP_RULE);
                    if (!TextUtils.isEmpty(nid)) {
                        // TODO
                        MarketAPI.reportIftttResult(getApplicationContext(), mProductId, nid, rule,
                                Constants.REPORT_TYPE_REVIEW_DETAIL);
                    }
                }
                if (TextUtils.isEmpty(mProductSource)) {
                    mProductSource = Constants.SOURCE_TYPE_GFAN;
                }
                getSupportLoaderManager().initLoader(MarketAPI.ACTION_GET_PRODUCT_DETAIL, null, this);
            } else {
                // 通过产品包名来获取内容
                getSupportLoaderManager().initLoader(MarketAPI.ACTION_GET_DETAIL, null, this);
            }
        }
        mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
        mProgressBar.setIndeterminateDrawable(new LoadingDrawable(this));
        mProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TCAgent.onResume(this);
    }
  
    @Override
    protected void onPause() {
        super.onPause();
//        TCAgent.onPause(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // 创建产品详细页的菜单（分享）
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.product_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case android.R.id.home:
                onBackPressed();
                return true;

            case R.id.menu_share:

                Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                        Constants.DETAIL_SHARE);
                if (mProduct != null) {
                    Utils.share(this, mProduct.getName(), mProduct.getPid());
                }
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 初始化ActionBar
     */
    private void initActionBar(String title) {
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayShowTitleEnabled(true);
        mActionBar.setTitle(title);
    }

    @Override
    public Loader<ApiResponse> onCreateLoader(int i, Bundle bundle) {

        if (MarketAPI.ACTION_GET_PRODUCT_DETAIL == i) {

            return MarketAPI.initProductDetailWithPId(getApplicationContext(),
                    mProductId, mProductSource);

        } else if (MarketAPI.ACTION_GET_DETAIL == i) {

            return MarketAPI.initProductDetailWithPackageName(getApplicationContext(),
                    mProductPackageName, mProductSource);
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mProductFragment = null;
        mProduct = null;
        mProductName = null;
        mProductId = null;
        mProductPackageName = null;
        mProductSource = null;
        mProduct = null;
        mProgressBar = null;
        mHandler = null;
    }

    @Override
    public void onLoadFinished(Loader<ApiResponse> productDetailLoader,
            ApiResponse apiResponse) {

        if (apiResponse.status == ApiResponse.STATUS_LOGIC_ERROR
                || apiResponse.status == ApiResponse.STATUS_TIMEOUT_ERROR) {
            Utils.makeEventToast(getApplicationContext(), getString(R.string.label_not_found),
                    false);
            finish();
            return;
        }

        switch (apiResponse.action) {

            case MarketAPI.ACTION_GET_DETAIL:
            case MarketAPI.ACTION_GET_PRODUCT_DETAIL: {

                if (mProduct == null) {
                    mProduct = (ProductDetail) apiResponse.result;
                    mHandler.sendEmptyMessage(ACTION_LOAD_DETAIL);
                }
                break;
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<ApiResponse> productDetailLoader) {
        // do nothing
    }


    @Override
    public void onScrollChanged(int scrollX, int scrollY) {

//        if (scrollY >= 0) {
//
//            final RelativeLayout infoLayout = (RelativeLayout) findViewById(R.id.app_info_layout);
//            final TabWidget tabWidget1 = (TabWidget) findViewById(android.R.id.tabs);
//            int infoHeight = infoLayout.getHeight();
//            int tabWidgetHeight = tabWidget1.getHeight();
//
//            if (scrollY <= infoHeight) {
//                FrameLayout.LayoutParams infoParams = (FrameLayout.LayoutParams) infoLayout.getLayoutParams();
//                infoParams.topMargin = - scrollY;
//                infoLayout.setLayoutParams(infoParams);
//                infoLayout.layout(0, -scrollY, infoLayout.getWidth(), infoHeight - scrollY);
//                tabWidget1.layout(0, infoHeight - scrollY, tabWidget1.getWidth(), tabWidgetHeight + infoHeight - scrollY);
//
//                Utils.E("move info>>>>>>>>>>>>>>>");
//
//            } else if (tabWidget1.getTop() != 0) {
//                infoLayout.layout(0, -infoHeight, infoLayout.getWidth(), 0);
//                tabWidget1.layout(0, 0, tabWidget1.getWidth(), tabWidgetHeight);
////                infoLayout.animate().setDuration(300).translationY(-infoHeight);
////                tabWidget1.animate().setDuration(300).translationY(0);
//                FrameLayout.LayoutParams infoParams = (FrameLayout.LayoutParams) infoLayout.getLayoutParams();
//                infoParams.topMargin = - infoHeight;
//                infoLayout.setLayoutParams(infoParams);
//
//                Utils.E("move tab>>>>>>>>>>>>>>>");
//
//            } else {
//
//                Utils.E("noaction >>>>>>>>>>>>>>>");
//            }
//        }
    }

    /*
     * 处理二维码消息
     */
    private boolean checkBarcode(Intent intent) {
        Uri uri = intent.getData();
        if (uri != null) {
            if (uri.getScheme().equals("market")) {
                String pkgName = uri.getQueryParameter("id");
                getSupportLoaderManager().initLoader(MarketAPI.ACTION_GET_DETAIL, null, this);
                return false;
            }

            String authority = uri.getAuthority();
            if ("download".equalsIgnoreCase(authority)) {
                mProductId = uri.getQueryParameter(ACTION_PID);
                mProductName = uri.getQueryParameter(PARAM_TITLE);
//                mProductIcon = uri.getQueryParameter(PARAM_ICON);
                // TODO
//                MarketAPI.getDownloadUrl(this, this, mPid, Constants.SOURCE_TYPE_GFAN);
                return false;
            }

            HashMap<String, String> params = Utils.parserUri(uri);
            if (params != null) {

                String query = params.get("p");
                if (!TextUtils.isEmpty(query)) {
                    String[] temp = query.split(":");
                    if (temp == null || temp.length < 2) {
                        return true;
                    }
                    String key = temp[0];
                    String value = temp[1];
                    if (ACTION_PID.equalsIgnoreCase(key)) {
                        mProductId = value;
                        getSupportLoaderManager().initLoader(MarketAPI.ACTION_GET_PRODUCT_DETAIL, null, this);
                        return false;
                    } else if (ACTION_PACKAGE_NAME.equalsIgnoreCase(key)) {
                        mProductPackageName = value;
                        getSupportLoaderManager().initLoader(MarketAPI.ACTION_GET_DETAIL, null, this);
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public final static int DIALOG_PURCHASE = 1;
    public final static int DIALOG_NO_BALANCE = 2;

    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_PURCHASE:
                return DialogUtil.newEnsurePurchaseDialog(this, id,
                        getString(R.string.hint_purchase, mProduct.getPrice()));
            case DIALOG_NO_BALANCE:
                return DialogUtil.newInsufficientBalanceDialog(this, id,
                        getString(R.string.warning_no_balance));
            default:
                break;
        }
        return null;
    }

    /**
     * 购买商品
     */
    public void purchaseProduct(String password) {
        MarketAPI.purchaseProduct(this, this, mProduct.getPid(), password);
    }

    /**
     * 前往充值页
     */
    public void gotoDepositPage() {
        final String type = mSession.getDefaultChargeType();
        if (type == null) {
            final Intent intent = new Intent(getApplicationContext(), ChargeTypeListActivity.class);
            intent.putExtra("payment", mProduct.getPrice());
            startActivity(intent);
        } else {
            final Intent intent = new Intent(getApplicationContext(), PayMainActivity.class);
            intent.putExtra("type", type);
            intent.putExtra("payment", mProduct.getPrice());
            startActivity(intent);
        }
    }


    @Override
    public void onSuccess(int method, Object obj) {

        if (method == MarketAPI.ACTION_PURCHASE_PRODUCT) {
            // 购买成功，同步购买记录
            BuyLog buyLog = new BuyLog();
            buyLog.pId = mProduct.getPid();
            buyLog.packageName = mProduct.getPackageName();
            DBUtils.insertBuyLog(getApplicationContext(), buyLog);
            mProductFragment.download();
        }
    }

    @Override
    public void onError(int method, int statusCode) {
        if (method == MarketAPI.ACTION_PURCHASE_PRODUCT) {
            if (219 == statusCode) {
                // NoEnoughCredit
                if (!isFinishing()) {
                    showDialog(DIALOG_NO_BALANCE);
                }
            } else if (212 == statusCode) {
                // 密码错误
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.hint_purchase_password_error), false);
            } else {
                // other error
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.hint_purchase_failed), false);
            }
        }
    }
}